from apscheduler.schedulers.background import BackgroundScheduler
from django_apscheduler.jobstores import DjangoJobStore, register_events
from django.utils.timezone import now
from django_apscheduler.models import DjangoJobExecution
import logging
from matrix.mytools import iot_cront
logger = logging.getLogger(__name__)


def my_job():
    print(f"Job executed at {now()}")


def start_scheduler():
    scheduler = BackgroundScheduler()
    scheduler.add_jobstore(DjangoJobStore(), "default")

    # 添加任务
    scheduler.add_job(
        iot_cront.run,
        'interval',
        seconds=120,
        id="my_job",
        replace_existing=True,
    )

    register_events(scheduler)

    try:
        logger.info("Starting scheduler...")
        scheduler.start()
    except KeyboardInterrupt:
        logger.info("Stopping scheduler...")
        scheduler.shutdown()
        logger.info("Scheduler shut down successfully!")